package com.zhike.api.controller.user;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zhike.common.constant.Constants;
import com.zhike.common.dto.BlacklistAddDTO;
import com.zhike.common.dto.BlacklistInDTO;
import com.zhike.common.dto.BlacklistToUidDTO;
import com.zhike.common.dto.PropertySwitchDTO;
import com.zhike.common.dto.R;
import com.zhike.common.dto.UserRosterVO;
import com.zhike.common.dto.UserOtherInfoDTO;
import com.zhike.common.dto.UserPasswdDTO;
import com.zhike.common.dto.UserPersonalSignatureDTO;
import com.zhike.common.dto.UserQueryDTO;
import com.zhike.common.dto.UserUpdateDTO;
import com.zhike.common.enums.ResultCode;
import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.model.ChatSession;
import com.zhike.common.model.Roster;
import com.zhike.common.utils.RedisService;
import com.zhike.common.utils._Utils;
import com.zhike.common.vo.BlacklistVO;
import com.zhike.common.vo.RosterVO;
import com.zhike.common.vo.UserInfo4Cache;
import com.zhike.common.vo.UserInfoVO;
import com.zhike.service.friends.IFriendsService;
import com.zhike.service.messages.IChatSessionService;
import com.zhike.service.system.ISystemService;
import com.zhike.service.user.IUserBlacklistService;
import com.zhike.service.user.IUserService;
import com.zhike.utils.cache.UsersInfoCacheProvider;
import com.zhike.utils.file.FileAvatar;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("api/zkim/user")
@Api(tags = "用户模块")
public class UserController {

    @Resource
    private IUserService userService;

    @Autowired
    private ISystemService systemService;

    @Autowired
    private IUserBlacklistService userBlacklistService;

    @Autowired
    private IChatSessionService chatSessionService;

    @Autowired
    private UsersInfoCacheProvider usersInfoCacheProvider;

    @Autowired
    private FileAvatar fileAvatar;

    @Autowired
    private IFriendsService friendsService;

    @Autowired
    private RedisService redisService;

    // @ApiOperation(value = "用户注册接口", notes = "用户注册接口说明")
    // @PostMapping("userRegister")
    // public R<Boolean> userRegister(@RequestBody UserRegisterDTO dto,
    // HttpServletRequest req) {
    // return systemService.userRegister(dto, IpHelper.getIpAddr(req));
    // }

    @ApiOperation(value = "用户信息修改接口", notes = "只允许修改昵称和性别")
    @PostMapping("userUpdate")
    public R<Boolean> userUpdate(@Validated @RequestBody UserUpdateDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        return userService.userUpdate(uc.getFakeUid(), dto);
    }

    @ApiOperation(value = "重置用户密码接口")
    @PostMapping("userResetPassword")
    public R<Boolean> userUpdatePassword(@Validated @RequestBody UserPasswdDTO dto) {
        return userService.userUpdatePasswd(dto);
    }

    @ApiOperation(value = "用户个性签名信息修改接口")
    @PostMapping("userUpdatePersonalSignature")
    public R<Boolean> userUpdatePersonalSignature(@Validated @RequestBody UserPersonalSignatureDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        return userService.userUpdatePersonalSignature(uc.getFakeUid(), dto);
    }

    // @ApiOperation(value = "用户其它说明修改接口")
    // @PostMapping("userUpdateOtherInfo")
    public R<Boolean> userUpdateOtherInfo(@RequestBody UserOtherInfoDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        return userService.userUpdateOtherInfo(uc.getFakeUid(), dto);
    }

    @ApiOperation(value = "用户个人信息", response = UserRosterVO.class)
    @PostMapping("getUserInfo")
    public R<UserInfo4Cache> getUserInfo() {
        UserInfo4Cache uc = systemService.getUserInfo();
        return R.success(uc);
    }

    @ApiOperation(value = "用户详情数据", notes = "用户通讯录中他人的信息")
    @GetMapping("getUserInfoById")
    public R<UserInfoVO> getUserInfoById(@RequestParam("uid") String fakeUid) {
        UserInfoVO vo = userService.getUserByUserId(fakeUid);
        if (vo == null) {
            return R.rsp(ResultCode.USER_NOT_EXSIT);
        }
        UserInfo4Cache uc = systemService.getUserInfo();
        // 标星
        Roster roster = friendsService.selectRoster(uc.getFakeUid(), fakeUid);
        if (roster != null) {
            vo.setStar(roster.getIsStar());
        }
        // 置顶
        ChatSession cs = chatSessionService.selectChatSession(uc.getFakeUid(), fakeUid);
        vo.setIsTop(cs == null ? 0 : cs.getIsTop());
        vo.setNodisturb(cs == null ? 0 : cs.getNodisturb());

        // 是否好友关系
        for (RosterVO r : uc.getRosterList()) {
            if (r.getFriendUserUid().equals(fakeUid)) {
                vo.setIsFriend(true);
                break;
            }
        }

        return R.success(vo);
    }

    @ApiOperation(value = "获取IM在线用户数")
    @GetMapping("getOnlineUserCount")
    public R<Long> getOnlineUserCount() {
        return R.success(redisService.sSize(Constants.USER_ONLINE_LIST));
    }

    @ApiOperation(value = "搜索用户", notes = "使用账号或手机号搜索")
    @PostMapping("queryUser")
    public R<UserRosterVO> queryUserByPhone(@Validated @RequestBody UserQueryDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();

        UserRosterVO entity = userService.queryUserInfo(dto.getSearchText());
        if (entity != null) {
            UserInfo4Cache target = usersInfoCacheProvider.get(entity.getFakeUid());
            if (_Utils.isPhoneNumber(dto.getSearchText().trim())) {
                if (null != target && target.getAllowPhoneSearch().equals(YesNoEnum.NO.getValue().toString())) {
                    return R.rsp(ResultCode.USER_NOT_EXSIT);
                }
            } else {
                if (null != target && target.getAllowNicknameSearch().equals(YesNoEnum.NO.getValue().toString())) {
                    return R.rsp(ResultCode.USER_NOT_EXSIT);
                }
            }

            // 是否好友关系
            Integer friendCount = friendsService.queryFriendsCountByUidFriendUid(uc.getFakeUid(),
                    entity.getFakeUid());
            entity.setIsFriend(friendCount > 0);
            entity.setStar(null == entity.getStar() ? "0" : entity.getStar());
            return R.success(entity);
        }
        return R.rsp(ResultCode.USER_NOT_EXSIT);

    }

    @ApiOperation(value = "查询我的黑名单")
    @PostMapping("queryBlacklist")
    public R<List<BlacklistVO>> queryBlacklist() {
        UserInfo4Cache uc = systemService.getUserInfo();
        List<BlacklistVO> list = userBlacklistService.queryMyBlacklist(uc.getFakeUid());
        return R.success(list);
    }

    @ApiOperation(value = "加入黑名单")
    @PostMapping("addBlacklist")
    public R<Boolean> addBlacklist(@Validated @RequestBody BlacklistAddDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        return R.success(userBlacklistService.addBlacklist(uc.getFakeUid(), dto));
    }

    @ApiOperation(value = "从黑名单移出")
    @PostMapping("cancelBlacklist")
    public R<Boolean> canelBlacklist(@Validated @RequestBody BlacklistToUidDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        return R.success(userBlacklistService.cancelBlacklist(uc.getFakeUid(), dto.getToUid()));
    }

    @ApiOperation(value = "是否在黑名单中", notes = "true在黑名单中 false不在黑名单中")
    @PostMapping("isInBlacklist")
    public R<Boolean> isInBlacklist(@Valid @RequestBody BlacklistInDTO dto) {
        return R.success(userBlacklistService.checkInBlacklist(dto.getFromUid(), dto.getToUid()));
    }

    @ApiOperation(value = "打开/关闭", notes = "参数way:verficate(加我为朋友需验证) notify(消息通知) account(通过账号搜索到我); " +
            "phone:(通过手机搜索到我) group(通过群聊加我) qr(通过二维码加我) card(通过名片加我)\n ")
    @PostMapping("setSwitch")
    public R<Boolean> setSearchSwitch(@Validated @RequestBody PropertySwitchDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        return R.success(userService.updateUserSwitch(uc.getFakeUid(), dto.getWay(), dto.getAction()));
    }

    @ApiOperation(value = "用户头像", notes = "用户头像下载地址")
    @GetMapping("avatar/{userId}")
    public R<String> getUserAvatar(@PathVariable("userId") String userId) {
        return R.success(fileAvatar.getUserAvatarUrl(userId));
    }

}
